package com.iot08.api.service;

import com.iot08.api.vo.request.RelatedAccountReqVO;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.DeviceToken;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2020/11/26 10:46
 */
@Slf4j
@Service
public class DeviceTokenService extends BaseService<DeviceToken> {

    @Resource
    private AccountService accountService;

    /**
     * 绑定账号
     *
     * @param vo
     * @time: 2020/11/26 10:44
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap relatedAccount(RelatedAccountReqVO vo) {
        Account account = accountService.findById(vo.getOpenid());
        if (account == null) {
            log.error("Account is null. id={}. relatedAccount vo={}", vo.getOpenid(), vo);
            return ResponseMap.fail(ResponseEnum.STATUS2000.getCode(), ResponseEnum.STATUS2000.getMsg());
        }
        DeviceToken deviceToken = this.findById(vo.getDevicetoken());
        Date expiryAt = DateUtil.addDay(DateUtil.getUTCDate(), 7);
        if (deviceToken == null) {
            //添加
            if (StringUtil.isNotBlank(vo.getOpenid())) {
                long delNum = this.delByQuery(new Query(Criteria.where("openid").is(vo.getOpenid())));
                if (delNum > 0) {
                    log.info("删除{}个 已存在的devicetoken", delNum);
                }
            }
            //创建deviceToken
            DeviceToken dt = new DeviceToken();
            dt.setId(vo.getDevicetoken());
            dt.setA(vo.getOpenid());
            dt.setPackageName(vo.getPackageName());
            dt.setVersion(vo.getVersion());
            dt.setTime(DateUtil.nowTimestampToDouble());
            dt.setExpiryAt(expiryAt);
            dt.setAccesstoken(accountService.getAccesstoken(account));
            if (StringUtil.isNotBlank(vo.getVoip_devicetoken())) {
                dt.setVoipDevicetoken(vo.getVoip_devicetoken());
            }

            //每次iOS 设备打开APP都会调用此方法 新增标记集成mqtt的情况
            if (vo.getHaveMqtt() != null) {
                dt.setHaveMqtt(vo.getHaveMqtt());
            } else {
                dt.setHaveMqtt(0);
            }
            //保存记录
            try {
                this.save(dt);
            } catch (Exception e) {
                log.error("DeviceToken exception = {}. vo = {}", e.getMessage(), vo);
            }
        } else {
            //更新
            Update update = new Update();
            if (!vo.getOpenid().equals(deviceToken.getA())) {
                update.set("a", vo.getOpenid());
            }
            String accountToken = accountService.getAccesstoken(account);
            if (!accountToken.equals(deviceToken.getAccesstoken())) {
                update.set("accesstoken", accountToken);
            }
            if (!vo.getPackageName().equals(deviceToken.getPackageName())) {
                update.set("package", vo.getPackageName());
            }
            if (!vo.getVersion().equals(deviceToken.getVersion())) {
                update.set("version", vo.getVersion());
            }
            if (StringUtil.isNotBlank(vo.getVoip_devicetoken())) {
                update.set("voip_devicetoken", vo.getVoip_devicetoken());
            }

            if (StringUtil.isNotBlank(vo.getHaveMqtt())) {
                update.set("haveMqtt", vo.getHaveMqtt());
            } else {
                update.set("haveMqtt", 0);
            }
            update.set("t", DateUtil.nowTimestampToLong());
            update.set("expiryAt", expiryAt);
            this.updateById(vo.getDevicetoken(), update);
        }
        return ResponseMap.success();
    }

    /**
     * 清除绑定账号
     *
     * @param devicetoken
     * @param openid
     * @time: 2020/11/26 10:13
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap delRelatedAccount(String devicetoken, String openid) {
        if (StringUtil.isNotBlank(openid)) {
            long delNum = this.delByQuery(new Query(Criteria.where("a").is(openid)));
            if (delNum > 0) {
                log.info("删除{}个 已存在的devicetoken openid:{} ", delNum, openid);
            }
        }
        this.delById(devicetoken);
        return ResponseMap.success();
    }

}
